package com.funo.ehealth.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.funo.ehealth.bean.UserUpDown;
import com.funo.ehealth.exception.UnCaughtException;
import com.funo.ehealth.main.ListMgr;
import com.funo.ehealth.service.CPService;

/** 
 * CP上行信息同步线程
 * 
 * @version V1.1
 * @author zhangguangying
 * @date 2012-11-17
 */
public class CPMsgThread extends AbstractThread {
	
	/**
	 * CP上行信息重试线程日志记录器
	 */
	private static final Log log = LogFactory.getLog(CPMsgThread.class);
	/**
	 * 间隔时间
	 */
	private static final long INTERVAL = 5000L;
	/**
	 * 线程运行标识
	 */
	public boolean isRunning = true;
	
	public CPMsgThread(ThreadGroup group, String name) {
		super(group, name);
		// TODO Auto-generated constructor stub
	}
	
	/* (non-Javadoc)
	 * @see com.funo.ehealth.thread.AbstractThread#init()
	 */
	@Override
	public boolean init() {
		boolean result = true;
//		log.info("初始化CP上行信息同步线程...");
		return result;
	}

	/* (non-Javadoc)
	 * @see com.funo.ehealth.thread.AbstractThread#terminateHandler()
	 */
	@Override
	public void terminateHandler() {
		log.info("退出CP上行信息同步线程...");
		isRunning = false;
		
		synchronized (ListMgr.cpMsgList) {
			try{
				ListMgr.cpMsgList.notifyAll();
			}catch (IllegalMonitorStateException e) {
				log.error("CP上行信息同步线程ListMgr.cpMsgList.notifyAll()异常", e);
			}
		}
	}

	@Override
	public void run() {
		log.info("启动CP上行信息同步线程...");
		
		CPService cpService = new CPService();
		UserUpDown userUpDown = new UserUpDown();
		
		while (isRunning) {
			synchronized (ListMgr.cpMsgList) {
				if(ListMgr.cpMsgList == null || ListMgr.cpMsgList.size() <= 0){
					ListMgr.cpMsgList.notify();
					
					try {
						ListMgr.cpMsgList.wait();
					} catch (InterruptedException e) {
						log.error("CP上行信息同步线程ListMgr.cpMsgList.wait()异常");
						throw new UnCaughtException();
					}
				}
			}
			
			for (int i = 0; i < ListMgr.cpMsgList.size(); i++) {
				if(!isRunning){
					return;
				}
				userUpDown = (UserUpDown) ListMgr.cpMsgList.get(i);
				cpService.sendMsgToCp(userUpDown);
			}
			ListMgr.cpMsgList.clear();
				
			try {
				sleep(INTERVAL);
			} catch (InterruptedException e) {
				log.error("CP上行信息同步线程sleep异常" , e);
				throw new UnCaughtException();
			}
		}
	}

}
